package com.mojito.learn.module.concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 并发相关
 *
 * @author liufq
 * @since 2022/4/7 上午11:31
 */
public class ThreadPool {
    public static void main(String[] args) {
        Executors.newFixedThreadPool(4);
        Executors.newSingleThreadExecutor();
        Executors.newCachedThreadPool();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,
                5,
                1L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        CountDownLatch countDownLatch = new CountDownLatch(4);

        System.out.println("开始生成个报");
        try {
            for (int i = 1; i < 5; i++) {
                int finalI = i;
                threadPoolExecutor.execute(() -> {
                    try {
                        Thread.sleep(1000 * finalI);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "：生成个报第" + finalI + "成功");
                    countDownLatch.countDown();
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPoolExecutor.shutdown();
        }

        System.out.println("等待所有 PDF 生成成功后拼接成一个 PDF");
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("个报 PDF 生成成功");
    }
}
